<style>
.clearfix:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}
* html .clearfix{height:1%;}
*{padding: 0;margin: 0;font-size: 14px;}
.list-filter table{border-collapse:collapse;border-spacing:0;vertical-align: top;border: 1px solid #ddd;}
.list-filter table td{border: 1px solid #ddd;}
.list-filter .right{float: right;}
.list-filter li{list-style:none;}
.list-filter{font-size: 14px;}
.list-filter h2{font-weight: bold;padding: 10px;}
.filter dl{float: left;border: 1px solid #ddd;margin-right: 10px;margin-bottom: 10px;}
.filter dl dt{background: #eee;padding: 3px 10px;}
.filter dl ul{height: 120px;width: 200px;overflow-y: auto;}
.filter input{vertical-align: -2px;}
.filter li label{display: block;padding-left: 10px;padding-top: 5px;padding-bottom: 5px;border-bottom: 1px solid #eee;}
.filter label:hover{background: #f2f2f2;cursor: pointer;}
.res-table{max-height: 300px;overflow-y: auto;}
.res-table table{margin: 0!important}
.res-table table th{border: 1px solid #ddd;background: #eee;padding: 5px 10px;text-align: left;}
.res-table table td{padding:2px 10px;animation: font 3s .3s;}
@keyframes font {
    0%{background: #FFFACB;}
    100%{background: #fff;}
}
</style>
<@ms.html5>
     <@ms.nav title="保险产品属性增加" back=true>
        <@ms.saveButton  onclick="save()"/>
    </@ms.nav>
    <@ms.panel>
        <@ms.form name="articleForm" isvalidation=true>
            <@ms.hidden name="insId" value="${insurance.insId?default(0)}"/>
            <@ms.text name="title" colSm="2" width="400" label="保险名称"    title="保险名称" size="8"  placeholder="请输入保险名称"  value="${insurance.title?default('')}"  validation={"maxlength":"20","required":"true", "data-bv-notempty-message":"保险名称不能为空","data-bv-stringlength-message":"属性名称在20个字符以内!"}/>
			<@ms.checkboxlist colSm="2" name="property" label="保险属性" list=[{"key":"1","value":"关注"},{"key":"2","value":"严选"},{"key":"3","value":"推荐"}]  listKey="key"  listValue="value" />
            <@ms.number  max='10000000'    name="startPrice" colSm="2" width="400" label="最底价格"    title="最底价格" size="5"  placeholder="请录入最底价格"  value="${insurance.startPrice?default(0)}"  />
			
          <@ms.formRow colSm="2" label="保险栏目" width="400">
	            <@ms.treeInput treeId="inputTree" json="${columnList?default('')}" jsonId="categoryId" jsonPid="categoryCategoryId" jsonName="categoryTitle" inputName="insType"  inputValue="${insType}" buttonText="选择栏目" clickZtreeId="clickZtreeId(event,treeId,treeNode);" expandAll="true"  showIcon="true"/>
			</@ms.formRow>
			  <@ms.select label="保险公司" width="400" name="companyId" id="companySelect"  list=companyList  listValue="companyName"   listKey="companyId"     validation={"required":"true", "data-bv-notempty-message":"必选项目"}  value="${insurance.companyId?default(0)}"/>
			 <@ms.text name="keyword" colSm="2" width="400" label="保险关键词"    title="保险关键词" size="8"  value="${insurance.keyword?default('')}"  placeholder="请输入保险关键词"  />
			
            <@ms.formRow colSm="2" label="产品导航图" width="400" >
					<@ms.uploadImg path="" uploadFloderPath="insurance" inputName="smallImage" size="1" msg="提示:产品列表图,支持jpg格式"  imgs="${insurance.smallImage?default('')}"    />
			</@ms.formRow>
			 
			
			<!-- ################################商品属性 start -->
			
			 <div id="appCtrl">
        <div class="container list-filter clearfix">
            <div class="clearfix filter">
                <dl v-for="el in categolate">
                    <dt>{{el.label}}
                    </dt>
                    <dd>
                        <ul>
                            <li v-for="item in el.list">
                                <label>
                                    <input @change="getCombination" type="checkbox" v-model="el.selected" :value="item.id"/>
                                    {{item.name}}
                                </label>
                            </li>
                        </ul>
                    </dd>
                </dl>
            </div>
            <div class="res-table">
                <table>
                    <tr>
                        <th>{{tableData.length||0}}</th>
                        <th v-for="el in categolate" v-if="el.selected.length">{{el.label}}</th>
                        <th>价格</th>
                    </tr>
                    <tr v-for="(item,index) in tableData">
                        <td>{{index+1}}</td>
                        <td v-for="el in item.list">{{el.name}}</td>
                        <td>
                            <input @keyup="priceChange" v-model="item.price" placeholder="请输入价格">
                        </td>
                    </tr>
                </table>
            </div>
            <br>
            <br>
        </div>
   </div>
   <@ms.hidden id="propertyId" name="propertyId" value=""/>
			<!-- ################################商品属性 end -->
			<div class="form-group mf-form-group">
	<label class="col-sm-1 control-label "></label>
	  
	  <div class="ms-form-control ms-from-group-input col-sm-9 has-feedback">
	  	<ul class="nav nav-tabs" role="tablist">
		    <li role="presentation" class="active"><a href="#tabIndex1" aria-controls="tabIndex1" role="tab" data-toggle="tab">产品描述</a></li>
		    <li role="presentation"><a href="#tabIndex4" aria-controls="tabIndex4" role="tab" data-toggle="tab">产品明细</a></li>
		    <li role="presentation"><a href="#tabIndex2" aria-controls="tabIndex2" role="tab" data-toggle="tab">购买须知</a></li>
		    <li role="presentation"><a href="#tabIndex3" aria-controls="tabIndex3" role="tab" data-toggle="tab">常见问题</a></li>
		  </ul>
		  <div class="tab-content" style="margin-top: 10px">
		    <div role="tabpanel" class="tab-pane active" id="tabIndex1">
				<@ms.editor colSm="2" name="synopsis" width="100%"   content="${insurance.synopsis?default('')}" />
        
		    </div>
		    <div role="tabpanel" class="tab-pane " id="tabIndex4">
				<@ms.editor colSm="2" name="content"   content="${insurance.content?default('')}" />
        
		    </div>
		    <div role="tabpanel" class="tab-pane" id="tabIndex2">
		    	<@ms.editor colSm="2" name="notice"   content="${insurance.notice?default('')}" />
        
		    </div>
		    <div role="tabpanel" class="tab-pane" id="tabIndex3">
				<@ms.editor colSm="2" name="helptext"  content="${insurance.helptext?default('')}" />
        
		    </div>
		  </div>
	  </div>
</div>

        	
        	
        	
        
        </@ms.form>
    </@ms.panel>
</@ms.html5>
<script>

	$(function(){
		//默认选中
		<#if insurance.insId?default(0) != 0>
			var type="${insurance.property?default('')}";
			$("#articleForm input[name='property']").each(function(){
				if(type!=""){
					propertyType = type.split(",");
				  	for(i=0;i<propertyType.length;i++){
						if($(this).val()==propertyType[i]){
							$(this).attr("checked",'true');
						}
					}
				}
			});
		</#if>
	});
	
	//选择栏目后查询自定义模型
function clickZtreeId(event,treeId,treeNode){
	if(treeNode.columnType == 2){
		<@ms.notify msg="不能选择单篇栏目" />
		return false;
	}
	if(treeNode.isParent==true){
		<@ms.notify msg="不能选择父级栏目" />
		return false;
	}
} 


    var url = "${managerPath}/goods/insurance/save.do";
    if($("input[name = 'insId']").val() > 0){
        url = "${managerPath}/goods/insurance/update.do";
        $(".btn-success").text("更新");
    }
    //编辑按钮onclick
    function save() {
        $("#articleForm").data("bootstrapValidator").validate();
            var isValid = $("#articleForm").data("bootstrapValidator").isValid();
            if(!isValid) {
                <@ms.notify msg= "数据提交失败，请检查数据格式！" type= "warning" />
                return;
        }
         var priceValue = vm.getProductTableString();
        if(!priceValue){
                <@ms.notify msg= "价格录入不完整！" type= "warning" />
                return;
        }
        var btnWord =$(".btn-success").text();
        $(".btn-success").text(btnWord+"中...");
        $(".btn-success").prop("disabled",true);
       
       
 
        $('#propertyId').val(priceValue);
      
        $.ajax({
            type:"post",
            dataType:"json",
            data:$("form[name = 'articleForm']").serialize(),
            url:url,
            success: function(status) {
       
                if(status.result == true) { 
                    <@ms.notify msg="保存或更新成功" type= "success" />
                    location.href = "${managerPath}/goods/insurance/main.do?insType=${insType?default(0)}";
                }
                else{
                    <@ms.notify msg= "保存或更新失败！值不合规则"  type= "fail" />
                    location.href= "${managerPath}/goods/insurance/main.do?insType=${insType?default(0)}";
                }
            }
        })
    }    
</script>

<script>

    var categolate = ${proList?default('')};

    //categolate.forEach(function(el,index){
    //    categolate[index].selected = [18,19];
    //    categolate[index].check = false;
        // categolate[index].list = [{id:0,name:'不选'}].concat(categolate[index].list)
    //});
    categolate.forEach(function(el,index){
        categolate[index].selected = categolate[index].selected|| [];
        categolate[index].check = categolate[index].check||false;
        // categolate[index].list = [{id:0,name:'不选'}].concat(categolate[index].list)
    });

     	debugger;
    var vm = new Vue({
        el: '#appCtrl',

        data: function(){
            return {
                categolate:categolate,
                combination:[],
              //  oldTableData:[{"price":"200","list":[{"id":1001,"name":"10万以下","check":true,"type":"coverage"},{"id":2002,"name":"二年","type":"period"}]},{"price":"100","list":[{"id":1002,"name":"20万","type":"coverage"},{"id":2002,"name":"二年","type":"period"}]}]
                oldTableData:${priceList?default('[]')}
            }
        },

          computed: {
            categolateRes: function(){
                var res = [], item = {}, selectedObjArr=[], that = this;
                this.categolate.forEach(function(_categolate, index){
                    if(!_categolate.check&&_categolate.selected.length){
                        _categolate.selected.forEach(function(_selected, _selected_index){
                            item[_categolate.type] = that.getItem(_categolate.list, _selected);
                        })
                        res.push(item)
                    }
                });
                return res;
            },

            tableData: function(){
                var res = [], item = {}, oldTableData = this.oldTableData;
                this.combination.forEach(function(el,index){
                    item = {};
                    var cout = oldTableData.filter(function(p){
                        return p.price&&(JSON.stringify(p.list) == JSON.stringify(el))
                        })
                    cout = cout[0] || {};
                    item.price = cout.price||'';
                    item.list = el;
                    res.push(item);
                });
                return res;
            }
        },


        methods:{
            priceChange: function(){
                this.oldTableData = this.tableData;
            },

            getCombination: function(){
                this.combination =  this.calCombination(this.getSelectedObj());
            },

            calCombination:function(arr) {
                var count = arr.length - 1; 
                var tmp = [];
                var totalArr = [];// 总数组

                return doCombinationCallback(arr, 0);
                
                function doCombinationCallback(arr, curr_index) {
                    for(val of arr[curr_index]) {
                        tmp[curr_index] = val;
                        
                        if(curr_index < count) {
                            doCombinationCallback(arr, curr_index + 1);
                        }else{
                            totalArr.push(tmp);
                        }
                        oldTmp = tmp;
                        tmp = [];
                        for(index of oldTmp) {
                            tmp.push(index);
                        }
                    }
                    return totalArr;
                }
            },

            getProductTableString: function(){
                var noPrice = this.tableData.filter(function(el){
                    return ''===el.price
                })
                if(noPrice.length){
                    alert('还有产品价格未输入')
                    return false;
                }

                return JSON.stringify(this.tableData)
            },

            getSelectedObj: function(){
                var arr = [], itemArr=[], that = this, obj;
                this.categolate.forEach(function(el){
                    itemArr = [];
                    el.selected.forEach(function(_el){
                        obj = that.getItem(el.list, _el)
                        obj.type = el.type;
                        itemArr.push( obj );
                    });
                    itemArr.length&&arr.push(itemArr)
                })
                return arr;
            },

            getItem: function(arr, id){

                for(var i = 0, len = arr.length; i<len; i++){
                    if(arr[i].id==id)
                        return arr[i]
                }
                return [];
            }
	       
        },
        
        mounted: function(){
            this.getCombination();
        }
    })
</script>